package archer.back.controllers

import java.io.FileOutputStream
import java.nio.file.{ Files, Paths }
import java.util.UUID

import archer.back.utils.PoiUtils
import play.api.mvc.ControllerComponents
import utils._
import io.circe.syntax._
import io.circe.generic.auto._
import cats.implicits._
import models.TableData
import play.api.libs.circe.Circe
import play.api.libs.ws.WSClient

import scala.concurrent.Future
import scala.util.Properties

class CrawlResultController(
  controllerComponents: ControllerComponents,
  wsClient: WSClient,
  crawlResultService: CrawlResultService)
  extends BackController(controllerComponents)
  with Circe
  with ArcherHelper {

  implicit val ec = defaultExecutionContext

  def list(page: Int, limit: Int) = Action.async { implicit request =>
    crawlResultService.list(page = page, limit = limit).map { s =>
      Ok(s.asJson)
    }
  }

  def fetchExcel(planId: Int) = Action.async { implicit request =>
    val workbookF = crawlResultService.planToExce(planId)

    val parentPath = Paths
      .get(Properties.tmpDir)
      .resolve(UUID.randomUUID.toString)

    Files.createDirectories(parentPath)

    val path = parentPath.resolve("export.xls")

    workbookF.map { workbook =>
      workbook.write(new FileOutputStream(path.toFile))

      Ok.sendPath(path)
        .withHeaders(
          CONTENT_TYPE -> BINARY,
          CONTENT_DISPOSITION -> DownloadUtils
            .contentDispositionByName("网站抓取结果列表.xls"))
    }
  }

}
